//
//  LDYComposeViewController.swift
//  李东阳微博
//
//  Created by 李东阳 on 16/4/23.
//  Copyright © 2016年 李东阳. All rights reserved.
//

import UIKit

class LDYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
      setupUI()
        
      setupNav()
        
        
     
    }
    //MARK: - 设置视图
    private func setupUI(){
    
    self.view.backgroundColor = UIColor.yellowColor()
      
        view.addSubview(composeTextView)
        
        view.addSubview(composeToolBar)
        
        composeTextView.addSubview(composePickerView)
        

       composeTextView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
            
        }
        
        
       composePickerView.snp_makeConstraints { (make) -> Void in
        
        make.size.equalTo(CGSize(width: UIScreeonwidth - 20, height: UIScreeonwidth - 20))
        
        make.leading.equalTo(10)
        
        make.top.equalTo(composeTextView).offset(100)
        }
           //MARK:监听 - toolBar 按钮点击
        composeToolBar.composeToolBarColsure = { [weak self] (type: LDYComposeToolBarType) in
        
            switch type{
                //图片按钮
            case .picture:

                self?.selectImage()
                //@按钮
            case .Mention:
                print("12")
                //#按钮
            case .Trend:
                print("123")
                //表情按钮
            case .Emoticon:
               self!.switchKeyBoard()
                //添加按钮
            case .Add:
                print("12345")
            
        
            }
            
        }
       
        //监听弹出图片控制器
        composePickerView.AddButtonClosure = {
        [weak self ] in
            
            self?.selectImage()
        }
  NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }

    func KeyboardWillChangeFrame(nsoti:NSNotification){
    
        //获取键盘的rect
        let rect = (nsoti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新composeToolBar约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - ScreenHeight)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    
        
    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //MARK: - 设置导航栏
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
 
   
    
    //MARK: - 懒加载控件
    private lazy var titleView:UILabel = {
    
    //用户昵称
    let name =  LDYUserAccountTools.userAccountTools.userAccount?.screen_name ?? ""
        
      let titleString = "发微博\n\(name)"
        
       //获取range
       let range = (titleString as NSString).rangeOfString(name)
        
        let attr = NSMutableAttributedString(string: titleString)
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        
         attr.addAttribute(NSForegroundColorAttributeName, value:myTintColor, range: range)
        
        
        let lab = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.sizeToFit()
        
        return lab
        
    }()
    
    
    private lazy var composePickerView:LDYComposePickerView = {
        
    let pic = LDYComposePickerView()
        
        return pic
    
    }()
    
    
    private lazy var composeToolBar: LDYComposeToolBar = {
    
    let ba = LDYComposeToolBar()
        
        return ba
    
        }()
    
    private lazy var composeTextView: LDYComposeTextView = {
    
    let view = LDYComposeTextView()
        
      view.font = UIFont.systemFontOfSize(16)
        
       view.placeHolder = "春眠不觉晓!处处蚊子咬!头上一个包!腿上一个包!饿了吃一个!一个吃不饱!"
       view.delegate = self
       view.alwaysBounceVertical = true
       
        
    return view
    }()
    
    //自定义表情键盘
    private lazy var emoticonKeyboard:LDYEmoticonKeyboardView = {
    
    let view = LDYEmoticonKeyboardView()
        
        view.frame = CGRect(x: 0, y: 0, width: UIScreeonwidth , height: 214)
        
        return view
        
    }()
    
    //MARK: - 取消按钮的点击事件
    @objc func cancel(){
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    //MARK: - 发送按钮的点击事件
    @objc func send(){
    
    print("发送按钮")
    
    }
    

}





//MARK: - UITextViewDelegate

extension LDYComposeViewController: UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
       
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()

        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }

}
//MARK: - 处理toolbar 里面的按钮点击事件
extension LDYComposeViewController{
    //选择图片
    func selectImage() {
        
        let pickerVc = UIImagePickerController()
        
        pickerVc.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera ){
        
        
        }else{
            print("不能打开照相机")
          presentViewController(pickerVc, animated: true, completion: nil)
        }
        
      
        
    }
    
    
    //切换键盘
    func switchKeyBoard(){
    
        if composeTextView.inputView == nil{
        //表情键盘
             composeTextView.inputView = emoticonKeyboard
            composeToolBar.isEmoticon = true
        }else{
        
            //系统键盘
             composeTextView.inputView = nil
            composeToolBar.isEmoticon = false
        }
        
        //刷新inputViews
       composeTextView.reloadInputViews()
        //当我们点击的时候 叫键盘弹出
        composeTextView.becomeFirstResponder()
    }

}

extension LDYComposeViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //处理压缩图片
         let scaleImage  = getImageScale(image, width: 600)
        
        
        composePickerView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //处理压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
    
        if image.size.width < width{
        
        return image
        }
        
    /*
        1200 400  1200 /400 = 600/200
        600  200
    */
        let height = (image.size.height * width) / image.size.width
    
    //开启图形上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
       
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
      //渲染
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        
        
    //关闭图形上下文
        return result
    }
    
//    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
//        print("点击取消按钮了")
//    
//    }

}






